package com.pig4cloud.pig.module.controller.intermediary;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.emoji.EmojiUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.intermediary.Intermediary;
import com.pig4cloud.pig.module.api.entity.intermediary.IntermediaryImg;
import com.pig4cloud.pig.module.api.entity.property.PropertyUser;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.intermediary.IIntermediaryImgService;
import com.pig4cloud.pig.module.service.intermediary.IIntermediaryService;
import com.pig4cloud.pig.module.service.property.IPropertyUserService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 中介信息（房屋、车位）Controller
 *
 * @author ruoyi
 * @date 2022-08-20
 */
@Validated
@Api(value = "中介信息（房屋、车位）控制器", tags = {"中介信息（房屋、车位）管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/intermediary")
public class IntermediaryController {

    private final IIntermediaryService intermediaryService;

    private final IIntermediaryImgService intermediaryImgService;

    private final IWxUserService wxUserService;

    private final IPropertyUserService propertyUserService;

    /**
     * 查询中介信息
     */
    @ApiOperation("查询中介信息（房屋、车位）列表")
    @PreAuthorize("@pms.hasPermission('module:intermediary:list')")
    @GetMapping("/list")
    public TableDataInfo<Intermediary> list(@Validated Intermediary intermediary) {
        QueryWrapper<Intermediary> qw = new QueryWrapper<>();
        if(intermediary.getEstateId()!=null){
            qw.eq("estate_Id",intermediary.getEstateId());
        }
        if(intermediary.getCheckState()!=null){
            qw.eq("check_state",intermediary.getCheckState());
        }else {
            qw.eq("check_state",0);
        }
        if(intermediary.getInfoType()!=null){
            qw.eq("info_type",intermediary.getInfoType());
        }else {
            qw.eq("info_type",0);
        }
        TableDataInfo<Intermediary> td = PageUtils.buildDataInfo(intermediaryService.page(PageUtils.buildPage(),qw));
        List<Intermediary> list = td.getData();
        for (Intermediary list1:list){
            WxUser wxUser = wxUserService.findById(list1.getUserId());
            list1.setUserName(EmojiParser.parseToUnicode(wxUser.getNickName()));
        }
//        list.forEach(user->{
//            if(StrUtil.isNotEmpty(user.getUserName())){
//                user.setUserName(EmojiUtil.toUnicode(user.getUserName()));
//            }
//        });
        return td;
    }

    /**
     * 导出中介信息（房屋、车位）列表
     */
    /*@ApiOperation("导出中介信息（房屋、车位）列表")
    @PreAuthorize("@pms.hasPermission('system:intermediary:export')")
    @SysLog("中介信息（房屋、车位）")
    @GetMapping("/export")
    public R<Intermediary> export(@Validated Intermediary intermediary) {
        List<Intermediary> list = intermediaryService.list();
        // ExcelUtil<Intermediary> util = new // ExcelUtil<Intermediary>(Intermediary.class);
        return  list;// util.exportExcel(list, "中介信息（房屋、车位）");
    }*/

    /**
     * 获取中介信息（房屋、车位）详细信息
     */
    @ApiOperation("获取中介信息（房屋、车位）详细信息")
    @PreAuthorize("@pms.hasPermission('module:intermediary:query')")
    @GetMapping("/{id}")
    public R<Intermediary> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        Intermediary intermediary = intermediaryService.getById(id);
//        WxUser wxUser = wxUserService.findById(intermediary.getUserId());
        IntermediaryImg img=intermediaryImgService.findById(intermediary.getUserId());
//        intermediary.setUserName(wxUser.getNickName());
        if(StrUtil.isNotEmpty(intermediary.getUserName())){
            intermediary.setUserName(EmojiUtil.toUnicode(intermediary.getUserName()));
        }
        return R.ok(intermediary);
    }

    /**
     * 修改中介信息（房屋、车位）
     */
    @ApiOperation("修改中介信息（房屋、车位）")
    @PreAuthorize("@pms.hasPermission('module:intermediary:edit')")
    @SysLog("中介信息（房屋、车位）")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody Intermediary intermediary) {
        if(intermediary.getState()==1){
            if(intermediary.getCheckState()==2){
                intermediary.setState(3);
            }
        }
        if(intermediary.getState()==3){
            if(intermediary.getCheckState()==1){
                intermediary.setState(1);
            }
        }
        if(intermediary.getCheckState()==1){
            intermediary.setShenhe(4);
            intermediary.setShenheInfo(" ");
            QueryWrapper<PropertyUser> qw=new QueryWrapper<>();
            qw.eq("estate_id",intermediary.getEstateId());
            qw.eq("user_type",2);
            List<PropertyUser> user = propertyUserService.list(qw);
            if(user.size()>1){
                intermediary.setManagerSysName(user.get(0).getUserName());
                intermediary.setKefuSysUserId(user.get(0).getId());
                intermediary.setKefuWxUserId(user.get(0).getUserId());
                intermediary.setKefuPhone(user.get(0).getPhoneNum());
            }


            /*intermediary.setShenhe(4);
            intermediary.setShenheInfo(" ");
            intermediary.setManagerSysName(user.getUserName());
            intermediary.setKefuSysUserId(user.getId());
            intermediary.setKefuWxUserId(user.getUserId());
            intermediary.setKefuPhone(user.getPhoneNum());*/
        }
        if(intermediary.getCheckState()==2){
            if(intermediary.getShenhe()==null||intermediary.getShenheInfo()==null){
                return R.okByRow(0);
            }
        }

        return R.okByRow(intermediaryService.updateById(intermediary) ? 1 : 0);
    }

    /**
     * 删除中介信息（房屋、车位）
     */
    @ApiOperation("删除中介信息（房屋、车位）")
    @PreAuthorize("@pms.hasPermission('module:intermediary:remove')")
    @SysLog("中介信息（房屋、车位）")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(intermediaryService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
